/**
* 基础菜单 商品管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>爱心商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 爱心商品管理-->

    <el-card class="box-card" style="margin: 50px 10px">
      <!--       搜索筛选 -->
      <el-form :inline="true" class="word-search">
        <el-form-item label="搜索：" style="font-family: 隶体;font-weight:bold;">
          <el-input prefix-icon="el-icon-search" style="width: 300px;" v-model="search" clearable
                    placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="searchWord()">搜索</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</el-button>
        </el-form-item>
      </el-form>
      <!--       数据表格 -->
      <el-table :data="productsInfo" border style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
        <el-table-column prop="price" label="所需爱心币" width="180"></el-table-column>
        <el-table-column prop="description" label="商品描述"></el-table-column>
        <el-table-column prop="imageUrl" label="商品图片">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="`http://localhost:8077/share/hope/common/view-avatar?path=${scope.row.imageUrl}`"
              :preview-src-list="['http://localhost:8077/share/hope/common/view-avatar?path='+scope.row.imageUrl]">            </el-image>
          </template>

        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
                        <el-button size="mini" @click="selectById(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteLoveProduct(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      <!-- 编辑界面 -->
      <el-dialog :title="title" :visible.sync="editFormLoveProduct" width="30%" @click="closeDialog">
        <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
          <el-form-item label="商品名称" prop="name">
            <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="商品名称"></el-input>
          </el-form-item>
          <el-form-item label="所需爱心币" prop="price">
            <el-input size="small" v-model="editForm.price" auto-complete="off" placeholder="所需爱心币"></el-input>
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input size="small" v-model="editForm.description" auto-complete="off" placeholder="商品描述"></el-input>
          </el-form-item>
          <el-form-item label="商品图片">
<!--            <el-input size="small" v-model="editForm.imageUrl" auto-complete="off" placeholder="商品图片"></el-input>-->
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8077/share/hope/common/upload-avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="editForm.imageUrl" :src='`http://localhost:8077/share/hope/common/view-avatar?path=${editForm.imageUrl}`'
                   class="avatar" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button size="small" type="primary" class="title" @click="addLoveProduct()">保存</el-button>
        </div>
      </el-dialog>
    </el-card>

  </div>
</template>

<script>

import Pagination from '../../components/Pagination';
import {variableSave} from "../../api/userMG";
import qs from 'qs';

export default {
  data() {
    //价格校验
    var checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('爱心币不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          return callback(new Error('请输入数字值'));
        }
      }, 0); //延迟0秒
      return callback(); //条件满足
    };
    return {
      srcList:[],
      editFormLoveProduct: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        id:'',
        name: '',
        price: '',
        description: '',
        imageUrl:''
      },
      // rules表单验证
      rules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        price: [
          {
            validator: checkPrice, trigger: 'blur'
          }
        ],
        description: [
          {required: true, message: '请输入商品描述', trigger: 'blur'}
        ]
      },
      //列表数据
      productsInfo: [],
      //模糊查询数据
      search: "",
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      }
    }

  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {

  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    handleAvatarSuccess(res, file) {
      this.editFormLoveProduct=false
      this.editFormLoveProduct=true
      this.editForm.imageUrl = res.msg
      // console.log(this.editForm)

      // this.imgPath = res.msg
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    //获取数据 查询
    async queryProductsInfo() {
      const request = {
        'page': {
          'current': this.pageparm.currentPage,
          'size': this.pageparm.pageSize
        },
        'query': {
          'id':'',
          'name': this.search,
          'description':''
        }
      }
      this.$axios.post('products/page', request).then(res => {
        // console.log(res)
        if (res.data.code === 20000) { //成功
          // this.$message.success(res.data.msg);
          this.productsInfo = res.data.data.records
          // 分页赋值
          this.pageparm.currentPage = res.data.data.current
          this.pageparm.pageSize = res.data.data.size
          this.pageparm.total = res.data.data.total
        } else { //失败
          this.$message.error(res.data.msg);
        }
      })
    },
    //删除爱心商品
    deleteLoveProduct(id) {
      this.$confirm('删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var res = await this.$axios.get("products/delete?productId=" + id)
        if (res.data.code === 20000) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        await this.queryProductsInfo();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 编辑、增加 页面保存方法
    addLoveProduct() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          //调用后端的添加数据的接口，进行添加即可
          const data = {
              id:this.editForm.id,
              name: this.editForm.name,
              price: this.editForm.price,
              description: this.editForm.description,
              imageUrl: this.editForm.imageUrl
          }
          var url ='';
          if (this.title==='修改'){
            url='products/update'
          }else if (this.title==='新增'){
            url='products/create';
          }
          this.$axios.post(url, data).then(res => {
            if (res.data.code === 20000) {
              this.$message.success(res.data.msg);
              this.queryProductsInfo();
            } else {
              this.$message.error(res.data.msg);
            }
          })
        } else {
          this.$message.error("数据不合法，请检查！");
        }
        this.editForm = {}
        this.editFormLoveProduct = false;
      })
    },
    //根据id查询展示信息
    async selectById(id){
      this.title = '修改'
      const request = {
        'page': {
          'current': 1,
          'size': 1
        },
        'query': {
          'id': id,
          'name':'',
          'description':''
        }
      }
      this.$axios.post('products/page', request).then(res => {
        if (res.data.code === 20000) { //成功
          // this.$message.success(res.data.msg);
          this.editForm = res.data.data.records[0]
          this.editFormLoveProduct = true;
        } else { //失败
          this.$message.error(res.data.msg);
        }
      })
    },
    //添加打开弹框
    add() {
      this.title = '新增';
      this.editForm={};
      this.editFormLoveProduct = true;
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      this.queryProductsInfo()
    },
    // 搜索事件
    searchWord() {
      this.pageparm.currentPage = 1
      this.queryProductsInfo();
    },
    //行颜色动态变化
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row';
      } else if (rowIndex % 2 === 0) {
        return "success-row";
      }
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormLoveProduct = false
    }
  },
  //当前页码加载前执行的代码
  mounted() {
    this.queryProductsInfo()
  }
}
</script>

<style>
.word-search {
  margin-top: 13px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


